package com.gxan.web.servlet.training;

import com.alibaba.fastjson.JSONObject;
import com.gxan.utils.FileUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
import java.util.HashMap;

//上传文件到本地
@WebServlet("/training/uploadFileTraining")
@MultipartConfig
public class UploadFileTrainingServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HashMap<String, Object> maps = new HashMap<>();
        try {
            //获取前端请求参数  参数文件
            //获取前端文件
            Part headImg = request.getPart("file");
            //获取文件名
            String fileName = headImg.getSubmittedFileName();
            //变为唯一
            fileName = FileUtils.newFileName("training", fileName);
            HttpSession session = request.getSession();
            if (fileName == null) {
                maps.put("code", 400);
                maps.put("msg", "文件无法识别");
                JSONObject.toJSONString(maps);
            }
            //保存文件
            //获取当前项目发布路径
            String realPath = request.getServletContext().getRealPath("");//文件服务器
            //文件的相对路径
//            System.out.println(realPath);
            String path = "image/" + fileName;
//            System.out.println(path);
            //绝对路径
            String absolutePath = realPath + path;
            //直接把文件写入那个路径
            headImg.write(absolutePath);
            maps.put("code", 0);
            maps.put("msg", "succeed");
            maps.put("urI", fileName);
            response.getWriter().write(JSONObject.toJSONString(maps));
        } catch (Exception e) {
            maps.put("code", 1);
            maps.put("msg", "上传失败");
            response.getWriter().write(JSONObject.toJSONString(maps));
        }
    }
}